package com.hmdp.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.hmdp.constant.RedisConstants;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        //从redis查询商铺类型缓存
        List<String> shopTypeJsonList = stringRedisTemplate.opsForList().range(RedisConstants.RedisShopConstants.CACHE_SHOP_TYPE_KEY, 0, -1);

        //存在直接返回
        if (CollUtil.isNotEmpty(shopTypeJsonList)) {
            List<ShopType> shopTypeList = shopTypeJsonList.stream()
                    .map(shopTypeJson -> JSONUtil.toBean(shopTypeJson, ShopType.class))
                    .collect(Collectors.toList());
            return Result.ok(shopTypeList);
        }

        //查询数据库
        List<ShopType> shopTypeList = query().orderByAsc("sort").list();


        //把数据写入redis
        if (CollUtil.isNotEmpty(shopTypeList)) {
            List<String> jsonList = shopTypeList.stream()
                    .map(shopType -> JSONUtil.toJsonStr(shopType))
                    .collect(Collectors.toList());
            stringRedisTemplate.opsForList().leftPushAll(RedisConstants.RedisShopConstants.CACHE_SHOP_TYPE_KEY, jsonList);
            stringRedisTemplate.expire(RedisConstants.RedisShopConstants.CACHE_SHOP_TYPE_KEY,
                    RedisConstants.RedisShopConstants.CACHE_SHOP_TYPE_TTL,
                    TimeUnit.MINUTES);
        }

        return Result.ok(shopTypeList);
    }
}
